﻿using AutoMapper;
using MaterialManagement.API.Application.Command.ERP;
using MaterialManagement.Domain.ERP;
using MaterialManagement.ErrorCode;
using MaterialManagement.Infrastructure.Implement;
using MaterialManagement.Infrastructure.Interface;
using MediatR;

namespace MaterialManagement.API.Application.Handler.ERP
{
    public class CreateOutboundRecordHandler : IRequestHandler<CreateOutboundRecordCommand, APIResult<int>>
    {
        private readonly DatabaseContext database;
        private readonly IMapper mapper;

        public CreateOutboundRecordHandler(DatabaseContext database,IMapper mapper)
        {
            this.database = database;
            this.mapper = mapper;
        }
        public async Task<APIResult<int>> Handle(CreateOutboundRecordCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            if (request.Picks == null)
            {
                result.Message = "物料列表不能为空";
                result.Code = APIEnum.Fail;
                return result;
            }
            try
            {
                var res = await database.SqlSugar.Queryable<StorageRecordModel>().FirstAsync(x => x.PurchaseOrderCode == request.ProductionOrdersCode);
                if (res != null)
                {
                    result.Message = "已有此领料单";
                    result.Code= APIEnum.Fail;
                    return result;
                }
                await database.SqlSugar.Ado.BeginTranAsync();
                var recordModel = mapper.Map<OutboundRecordModel>(request);
                await database.SqlSugar.Insertable(recordModel).ExecuteCommandAsync();
                var picking = request.Picks.Select(p => new PickingModel
                {
                    PickingId = p.PickingId,
                    PickFormCode = request.PickFormCode,
                    MaterialCode = p.MaterialCode,
                    PickingQuantity = p.PickingQuantity,
                    WarehouseCode = p.WarehouseCode,
                    IsDel = false
                }).ToList();
                int r = await database.SqlSugar.Insertable(picking).ExecuteCommandAsync();
                await database.SqlSugar.CommitTranAsync();
                result.Message = $"成功创建领料单并关联 {r} 个物料";
                result.Code = APIEnum.Ok;
                result.Data = r;
                return result;
            }
            catch (Exception ex)
            {

                throw;
            }

        }
    }
}
